package com.justnow.offer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author justnow
 * Created on 2020-09-04
 * Description
 * 二维数组，顺时针打印
 */
public class Bilibili02 {
    public int[] SpiraMatrix(int[][] matrix) {
        List<Integer> list = new ArrayList<>();

        if (matrix == null || matrix.length == 0)
            return new int[]{};

        int rows = matrix.length; //行数
        int cols = matrix[0].length; //列数
        int i = 0;

        int count = (Math.min(rows, cols) + 1) / 2; //


        while (i < count) {

            for (int j = i; j < cols - i; j++) {
                list.add(matrix[i][j]);
            }

            for (int j = i+1; j < rows - i; j++) {
                list.add(matrix[j][cols-1-i]);
            }

            for (int j = (cols-1)-(i+1); j >= i && (rows-1-i != i); j--) {
                list.add(matrix[rows-1-i][j]);
            }

            for (int j = rows-1-i-1; j >= i+1 && (cols-1-i!=i);j--) {
                list.add(matrix[j][i]);
            }

            i++;
        }
        int[] array = new int[cols * rows];
        for (int j = 0; j < list.size(); j++) {
            array[j] = list.get(j);
        }
        return array;
    }
}
